﻿using GenericHtml;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using WLFramework.Data;
using WLFramework.Data.Linq;
using WLFramework.DataAccess;
using WLFramework.Json;
using WLFramework.Validation;
using WLFramework.Web;

namespace SampleSite.admin.ajax
{
    /// <summary>
    /// deleteModule 的摘要说明
    /// </summary>
    public class deleteModule : AjaxHttpHandler
    {
        private class InputData 
        {
            [Required]
            public int Id { get; set; }
        }

        public override void OnProcessRequest(HttpContext context)
        {
            InputData input;
            var errors = context.GetModel<InputData>(out input);
            if (errors.Count > 0)
                throw new Exception("输入的数据格式不正确");

            using (PermissionContext db = new PermissionContext())
            {
                var module = db.sys_ModuleList.Where(k => k.M_ID == input.Id).First();

                db.BeginTransaction();

                if (module.M_Level == 1)
                {
                    var children = db.sys_ModuleList.Where(k => k.M_ParentID == module.M_ID)
                                     .Select(k => k.M_ID);

                    db.sys_RoleModule.Where(k => children.Contains(k.M_ID))
                      .Set(k => k.M_State, 2)
                      .Update();

                    db.sys_ModuleList.Where(k => k.M_ParentID == module.M_ID)
                      .Set(k => k.M_State, 2)
                      .Update();
                }

                db.sys_RoleModule.Where(k => k.M_ID == module.M_ID)
                                 .Set(k => k.M_State, 2)
                                 .Update();
                db.sys_ModuleList.Where(k => k.M_ID == module.M_ID)
                                 .Set(k => k.M_State, 2)
                                 .Update();

                db.CommitTransaction();

                context.Response.Write(JSON.Instance.ToJSON(JSONResult.Success));
            }
        }
    }
}